package com.fin.quant.rpc.bean;


import io.grpc.ManagedChannel;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;

public class GrpcClientFactoryBean<T> implements FactoryBean<T> {

    private final Method factoryMethod;
    private final String serviceName; // Consul 注册服务名

    @Autowired
    private GrpcClientChannelFactory channelFactory;

    public GrpcClientFactoryBean(Method factoryMethod, String serviceName) {
        this.factoryMethod = factoryMethod;
        this.serviceName = serviceName;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T getObject() throws Exception {
        ManagedChannel channel = channelFactory.getChannel(serviceName);

        return (T) factoryMethod.invoke(null, channel);
    }

    @Override
    public Class<?> getObjectType() {
        return (Class<T>) factoryMethod.getReturnType();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
